const recorderManager = wx.getRecorderManager();
const options = {
  duration: 60000, // 指定录音的时长，单位 ms
  sampleRate: 16000, // 采样率
  numberOfChannels: 1, // 录音通道数
  encodeBitRate: 48000, // 编码码率
  format: 'pcm', // 音频格式
};

class AudioUtils {
  constructor() {
    this.token = '';
    this.filesize = 0;
    this.tempFilePath = '';
  }

  // 获取 token
  getToken(callback) {
    let ApiKey = 'bYGLHIAqUKgDiyxm5jkxLZyE'; // 你自己的apikey
    let SecretKey = 'SZFPRufqfQG2bgql34uVW1hsntfq31oB'; // 你自己的SecretKey
    const url = `https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id=${ApiKey}&client_secret=${SecretKey}`;
    
    wx.request({
      url: url,
      method: 'POST',
      success: (res) => {
        console.log("创建access_token成功", res);
        wx.setStorageSync('access_token', res.data.access_token);
        let time = new Date().getTime() + 2592000 * 1000; // 30天后的时间
        wx.setStorageSync('expires_in', time);
        this.token = res.data.access_token;
        if (callback) callback();
      },
    });
  }

  // 检查并获取 token
  checkToken(callback) {
    let token = wx.getStorageSync('access_token');
    let expires_in = wx.getStorageSync('expires_in');
    const currentTime = new Date().getTime();

    if (!token || currentTime > parseInt(expires_in)) {
      this.getToken(callback);
    } else {
      this.token = token;
      if (callback) callback();
    }
  }

  // 开始录音
  startRecording() {
    wx.authorize({
      scope: 'scope.record',
      success: () => {
        console.log("录音授权成功");
        recorderManager.start(options);
        recorderManager.onStart(() => {
          console.log('开始录音');
        });
      },
      fail: () => {
        console.log("录音失败");
      },
    });
  }

  // 停止录音
  stopRecording(callback) {
    recorderManager.stop();
    recorderManager.onStop((res) => {
      console.log('文件路径==', res);
      this.tempFilePath = res.tempFilePath;
      
      wx.getFileSystemManager().getFileInfo({
        filePath: this.tempFilePath,
        success: (res) => {
          this.filesize = res.size;
          console.log('文件长度', res);
          if (callback) callback();
        },
        fail: (res) => {
          console.log("读取文件长度错误", res);
        },
      });
    });
  }

  // 语音识别
  recognizeSpeech(successCallback, errorCallback) {
    wx.getFileSystemManager().readFile({
      filePath: this.tempFilePath,
      encoding: 'base64',
      success: (res) => {
        wx.request({
          url: 'http://vop.baidu.com/server_api',
          data: {
            token: this.token,
            cuid: "SZFPRufqfQG2bgql34uVW1hsntfq31oB",
            format: 'pcm',
            rate: 16000,
            channel: 1,
            speech: res.data,
            len: this.filesize,
          },
          headers: {
            'Content-Type': 'application/json',
          },
          method: 'POST',
          success: (res) => {
            if (res.data.result == '') {
              wx.showModal({
                title: '提示',
                content: '听不清楚，请重新说一遍！',
                showCancel: false,
              });
              return;
            }
            console.log("识别成功==", res.data);
            if (successCallback) successCallback(res.data.result);
          },
          fail: (res) => {
            console.log("失败", res);
            if (errorCallback) errorCallback(res);
          },
        });
      },
    });
  }
  
  // 语音合成
    textToSpeech(text) {
        return new Promise((resolve, reject) => {
          this.checkToken(() => {
            const url = `https://aip.baidubce.com/rpc/2.0/tts/v1/create?access_token=${this.token}`;
            const payload = {
              text: text,
              format: "mp3-16k",
              voice: 0,
              lang: "zh",
              speed: 5,
              pitch: 5,
              volume: 5,
              enable_subtitle: 0
            };
    
            wx.request({
              url: url,
              method: 'POST',
              data: payload,
              header: {
                'Content-Type': 'application/json',
                'Accept': 'application/json'
              },
              success: (res) => {
                console.log("语音合成任务创建成功", res);
                if (res.data.task_id) {
                  wx.setStorageSync('task_id', res.data.task_id);
                  resolve(res.data);
                } else {
                  reject(res);
                }
              },
              fail: (err) => {
                console.error("语音合成任务创建失败", err);
                reject(err);
              }
            });
          });
        });
      }
     // 查询语音合成结果
  querySpeechResult(taskId) {
      return new Promise((resolve, reject) => {
        this.checkToken(() => {
          const url = `https://aip.baidubce.com/rpc/2.0/tts/v1/query?access_token=${this.token}`;
          const payload = {
            task_ids: [taskId]
          };
  
          wx.request({
            url: url,
            method: 'POST',
            data: payload,
            header: {
              'Content-Type': 'application/json',
              'Accept': 'application/json'
            },
            success: (res) => {
              console.log("查询语音合成结果成功", res);
              resolve(res.data);
            },
            fail: (err) => {
              console.error("查询语音合成结果失败", err);
              reject(err);
            }
          });
        });
      });
    }
      
  
}

module.exports = AudioUtils;
